﻿using System.Collections.Generic;
using System.Linq;
using Fujitsu.JiraAnalysis.TrackingSystemAdapter;
using Fujitsu.JiraAnalysis.DAL;
using Fujitsu.JiraAnalysis.ReplicationService.SynchronizeExceptions;
using Fujitsu.JiraAnalysis.JiraRPC;

namespace Fujitsu.JiraAnalysis.ReplicationService.Synchronize
{
    public class IssuePrioritySync : SyncBase<RemotePriority,PriorityMapping> 
    {
        PriorityStorage issuePriorityStorage = new PriorityStorage();

        protected override SyncException GetSyncException(string projectName, int projectId, string projectKey)
        {
            return new IssuePrioritySyncException(projectName, projectId, projectKey);
        }

        protected override List<PriorityMapping> GetStorageItems(int projectId)
        {
            return issuePriorityStorage.GetIssuePriorityMappingForProject(projectId);
        }

        protected override List<RemotePriority> GetTrackSystemInfoItems(Project project, ITrackSystemInfo adapter)
        {
            return adapter.GetPriorities();
        }

        protected override PriorityMapping FindMatchInStorage(List<PriorityMapping> storageItems, RemotePriority trackSystemInfoItem, int projectId)
        {
            return storageItems.FirstOrDefault(i => i.JiraPriorityID.ToString() == trackSystemInfoItem.id && i.ProjectID == projectId);
        }

        protected override void Update(RemotePriority trackSystemItem, PriorityMapping priorityMapping)
        {
            if (priorityMapping.Name == trackSystemItem.name)
                return;
            issuePriorityStorage.UpdateResolutionName(priorityMapping.ProjectID, priorityMapping.JiraPriorityID, trackSystemItem.name);
        }
    }
}
